<template>
  <el-tabs class="tabs" >
    <el-tab-pane label="基本信息" v-model="activePane" class="tabs tab-item" >
 <!--      <template v-if="true">
      
      <div class="dialog" v-if="!isTeacher && !isExistClass && showCreateDialog">
        <div class="dialog-title">
          请完善选择班級信息
          <button class="dialog-close" @click="showCreateDialog=false"><i class="el-icon-close"></i></button>
        </div>
        <el-form label-width="100px" class="form">
          <el-form-item label="选择班级" prop="region">
            <el-select v-model="ruleForm.classId" placeholder="请选择班级">
              <el-option label="光电1701" value="1"></el-option>
              <el-option label="光电1702" value="2"></el-option>
              <el-option label="光源1701" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button class="btn" type="primary" @click="saveClass">保存</el-button>
            <el-button class="btn" @click="showCreateDialog=false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template> -->
    <el-form  :model="userForm" :label-position="labelPosition"  >
      <el-form-item class="userinfo-item" label="头像：">
        <my-upload @crop-success="cropSuccess" v-model="showCropper" :width="200" :height="200" img-format="png" :size="avatarSize"></my-upload>
        <img :src="userForm.avatarUrl">
        <el-button type="primary" size='small' @click="showImageCropper">设置</el-button>
      </el-form-item>
    <!-- <ul v-if="type==1" class="userinfo-content">
     -->
      <el-form-item class="userinfo-item" label="昵称："  >
        <el-input class="userinfo-item-value" v-model="userForm.nickname"  ></el-input>
      </el-form-item>
      <el-form-item class="userinfo-item" label="真实姓名："   >
        <el-input class="userinfo-item-value" v-model="userForm.real_name" :disabled="true"></el-input>
      </el-form-item>
      <!-- <el-form-item class="userinfo-item" label="修改头像："  :label-position="labelPosition">
        <img :src="img.length>0?img:userInfo.avatar" alt="点击修改" class="userinfo-avatar" @click="selectImg">
        <input type="file" accept="image/*" style="display: none" ref="img-picker" @change="showImg">
      </el-form-item> -->

      <!-- <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>  -->
      <!-- </el-form-item> -->

      <el-form-item class="userinfo-item" label="学校：">
        <el-select v-model="userForm.college_name" filterable @change="changeCollege"  >
          <el-option
            v-for="item in colleges"
            :key="item.id"
            :label="item.name"
            :value="item.name">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item class="userinfo-item" label="手机号：">
        <el-input class="userinfo-item-value" v-model="userInfo.phone" :disabled="true"></el-input>
      </el-form-item>
      
      <el-form-item class="userinfo-item" label="角色：" >
         <el-input class="userinfo-item-value" v-model="userForm.user_type" :disabled="true"> </el-input>
      </el-form-item>
      
      <!-- 学生部分 -->
        <el-form-item v-if= "userForm.user_type=='学生'" class="userinfo-item" label="班级：">
        <el-select v-model="userForm.class_name" filterable @change="changeClass"  >
          <el-option
            v-for="item in classes"
            :key="item.id"
            :label="item.name"
            :value="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if= "userForm.user_type=='学生'" class="userinfo-item" label="学号：">
        <el-input class="userinfo-item-value" v-model="userForm.student_number" ></el-input>
      </el-form-item>
      <!-- 老师部分 -->
      <el-form-item v-if= "userForm.user_type=='教师'" class="userinfo-item" label="职称：">
        <el-select v-model="userForm.academic_title" filterable @change="changeAcademicTitle"  >
          <el-option
            v-for="item in academic_titles"
            :key="item.key"
            :label="item.title"
            :value="item.title">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if= "userForm.user_type=='教师'" class="userinfo-item" label="工号：">
        <el-input class="userinfo-item-value" v-model="userForm.job_number" ></el-input>
      </el-form-item> 

      <el-form-item class="userinfo-item">
         <el-button @click="updateAccount" class="save-btn">保存</el-button>
      </el-form-item>

    <!-- <ul v-if="type==2" class="userinfo-content">
      <el-form class="right">
        <h3 class="form-title">修改密码</h3>
        <h4>原密码：</h4>
        <el-form-item>
          <el-input class="second-input" type="password" v-model="oldPassword" size="medium" placeholder="请输入原密码">
          </el-input>
        </el-form-item>
        <h4>新密码：</h4>
        <el-form-item>
          <el-input class="second-input" type="password" v-model="newPassword" size="medium" placeholder="请输入新密码">
          </el-input>
        </el-form-item>
        <h4>确认密码：</h4>
        <el-form-item>
          <el-input class="second-input" type="password" v-model="newPassword" size="medium" placeholder="请再次输入新密码"></el-input>
        </el-form-item>
        <el-form-item style="margin-top: -20px">
            <el-button @click="register" type="primary" size="mini" class="submit-btn">确定</el-button>
        </el-form-item>
      </el-form>
      <el-form class="right">
        <h3 class="form-title">更换手机号</h3>
        <h4>原手机号：</h4>
        <el-form-item>
          <el-input class="second-input" v-model="oldPhone" size="medium" placeholder="请输入原手机号码">
          </el-input>
        </el-form-item>
        <h4>验证码：</h4>
        <el-form-item>
            <el-input class="profile-verify-code" v-model="verify" size="medium" placeholder="请输入手机验证码"></el-input>
            <el-button @click="sendSms" :disabled="sendStatus" class="verify-btn" size="medium">{{ sendText }}</el-button>
        </el-form-item>
        <h4>新手机号：</h4>
        <el-form-item>
          <el-input class="second-input" v-model="newPhone" size="medium" placeholder="请输入新手机号码">
          </el-input>
        </el-form-item>
        <el-form-item style="margin-top: -20px">
            <el-button @click="register" type="primary" size="mini" class="submit-btn">确定</el-button>
        </el-form-item>
      </el-form>
    </ul> -->
  </el-form>
    </el-tab-pane>
    <!-- <el-tab-pane label="更多信息" name="advancedInfo">
        写一堆东西吧，更多信息
    </el-tab-pane>
    <el-tab-pane label="安全设置" name="securityInfo">
      写一堆东西吧，安全设置
    </el-tab-pane> -->
    
  </el-tabs>
</template>

<script>
import { sms, getColleges, getClass, getUserInfo, updateAvatar, updateClass, updateAccount } from '@/utils/api'
import myUpload from 'vue-image-crop-upload';

export default {
  name: 'Profile',
  components: {
      "my-upload": myUpload
    },
  data () {
    return {
      oldPhone: '',
      newPhone: '',
      phone: null,
      sendStatus: false,
      verify: '',
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
      type: 1,
      img: '',
      sendText: '获取验证码',
      imgFile: null,
      showCropper: false,
      avatarSize:2.1,
      showCreateDialog:true,
      ruleForm: {
        classId: null,
      },
      colleges: null,
      classes: null,

      activePane: "basicInfo",
      labelPosition: "left",
      academic_titles: [
        {key:'0', title:'讲师'},
        {key:'1', title:'副教授'},
        {key:'2', title:'教授'}
      ],
      userForm: {   
        role: null,
        user_type: null,
        nickname: null,
        real_name: null,  
        college_id: null,
        college_name: null,
        class_id: null,
        class_name: null,
        avatarUrl: null,
        student_number: null, 
        job_number: null,
        academic_title: null,
        position: null, 
      }
    }
  },
  
  async beforeMount() {
      //get all colleges

      var userInfo=this.$store.state.userInfo
      console.log(userInfo)
      this.userForm.nickname= userInfo.nickname
      this.userForm.real_name= userInfo.real_name
      this.userForm.college_id=userInfo.college0 ? userInfo.college0.id : -1
      this.userForm.college_name=userInfo.college0 ? userInfo.college0.name : ''
      if (userInfo.role=='1'){
        this.userForm.user_type='学生'
        this.userForm.student_number=userInfo.student.student_number

      }else if( userInfo.role=='2'){
        this.userForm.user_type='教师'
        if(userInfo.teacher.position=='1'){
          this.userForm.academic_title="讲师"
        }else if(userInfo.teacher.position=='2'){
          this.userForm.academic_title="副教授"
        }else if(userInfo.teacher.position=='3'){
          this.userForm.academic_title="教授"
        } 
        this.userForm.job_number=userInfo.teacher.job_number
      }
      this.userForm.role= userInfo.role
      console.log(this.userForm)
      let res= await getColleges()
      //this.colleges=res['result']
      
      if (res.error === '10') {
        this.colleges=res.result
      }
      else {
        this.$notify({
          title: '获取学校出错',
          type: 'error',
          message: res.result
        })
      }
      // get all classes of this college
      if (userInfo.role==="1")
      {
        // this.userForm.role="1"
        this.userForm.class_name=userInfo.student.class_name
        this.student_number=userInfo.student.student_number
        // this.$options.methods.getClasses(this.userForm.college_id) 
        let res=await getClass({college_id: userInfo.college0.id} )
        
        if (res.error === '10') {
          this.classes=res.result
        }
        else {
          this.$notify({
          title: '获取班级出错',
          type: 'error',
          message: res.result
          })
        }
      }
    },
  computed: {
    userInfo () {
      return this.$store.state.userInfo
    },
    userType () {
      return this.userInfo.role === '2' ? '教师' : '学生'
    },
    isTeacher () {
      return this.$store.getters.isTeacher
    },
    isExistClass(){
      console.log(this.$store)
      return this.$store.state.userInfo.class_id === null ? false : true
    }
  },

  methods: {
    changeInfoType(tab, event) {
        console.log(tab, event);
      },
    updateAvatarSuccess(){

    },
    async cropSuccess(imgDataUrl) {
        //  imgDataUrl其实就是经过base64转码过的图片
        // this.userForm.avatarUrl = imgDataUrl;
      console.log(imgDataUrl)//这里打印出来的是base64格式的资源，太长了
      let res=await updateAvatar({"avatar_base64":imgDataUrl})
      console.log(res)
      if (res.error === '10') {
        // this.=res.result
      }
      else {
        this.$notify({
          title: '头像上传失败！',
          type: 'error',
          message: res.result
        })
      }

        // // base64转blob格式
        // let arr = imgDataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        //   bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        // while (n--) {
        //   u8arr[n] = bstr.charCodeAt(n);
        // }
        // let bdata = new Blob([u8arr], { type: mime })
        // console.log(new Blob([u8arr], { type: mime })) ;//这里打印base64转成blob的资源，根据自己的项目需求去转吧

      },

    showImageCropper(){
      this.showCropper=!this.showCropper
    },

    async getClasses(college_id){
      if (this.userForm.role!=='1'){
          return 0
      }
      let res=await getClass({college_id: college_id} )
      console.log(res)
      if (res.error === '10') {
        this.classes=res.result
      }
      else {
        this.$notify({
          title: '获取班级出错',
          type: 'error',
          message: res.result
        })
      }
    },
    async updateAccount() {
      console.log(this.userForm)
      let res = await updateAccount(this.userForm)
      console.log(res)
      if (res.error==='10')
      {
        this.$store.commit('setUserInfo', res.result)
        if (res.error === '10') {
        this.$notify({
          title: '修改成功！',
          message: "用户信息修改成功！",
          type: 'success'
          })
        }
      }
       
    },
    beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt5M = file.size / 1024 / 1024 < 5;

        if (!isJPG && !isPNG) {
          this.$message.error('上传头像图片只能是 JPG和PNG 格式!');
        }
        if (!isLt5M) {
          this.$message.error('上传头像图片大小不能超过 5MB!');
        }
        return isJPG && isLt2M;
    },
    handleAvatarSuccess(file){
      this.imageUrl = URL.createObjectURL(file.raw);
    },

    selectImg() {
      this.$refs['img-picker'].click()
    },
    showImg(e) {
      if (e.target.files.length > 0) {
        this.imgFile = e.target.files[0]
        this.img = URL.createObjectURL(e.target.files[0])
      }
    },
    changeCollege: function(value) {
      console.log('changeCollege')
      var obj=this.colleges.find((item)=> item.name === value)
      this.userForm.college_name=obj.name
      this.userForm.college_id=obj.id
      this.getClasses(this.userForm.college_id)
      // console.log(obj)
    },
    changeClass: function (value) {
      var obj=this.classes.find((item)=> item.name === value)
      this.userForm.class_name=obj.name
      this.userForm.class_id=obj.id
      // console.log(obj)
    },
    changeAcademicTitle: function (value) {
      if(value=="讲师"){
          this.userForm.position="1"
        }else if(value=="副教授"){
          this.userForm.position="2"
        }else if(value=="教授"){
          this.userForm.position="3"
        } 

    },
    
    changeType(type) {
      this.type = type
    },
    async sendSms() {
      var reg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/
      if (this.phone) {
        if (!reg.test(this.phone)) {
          this.$notify({
            title: '发送失败',
            message: '请填写正确的手机号码',
            type: 'error'
          })
        } else {
          let res = await sms({phone: this.phone, is_for: '2'})
          if (!this.sendStatus) {
            if (res.error === '10') {
              this.$notify({
                title: '发送成功',
                message: `请查收`,
                type: 'success'
              })
              this.setTime(60)
            } else {
              this.$notify({
                title: '发送失败',
                message: res.result,
                type: 'error'
              })
            }
          }
        }
      } else {
        this.$notify({
          title: '发送失败',
          message: '手机号码还没填写呢',
          type: 'error'
        })
      }
    },
    setTime(countdown) {
      if (!countdown) {
        this.sendText = '获取验证码'
        this.sendStatus = false
      } else {
        this.sendText = '重新发送(' + countdown + ')'
        this.sendStatus = true
        countdown--
        setTimeout(() => {
          this.setTime(countdown)
        }, 1000)
      }
    },
    async submit() {
      if (this.img.length > 0) {
        let res = await updateAvatar(this.imgFile, this.userInfo.id)
        if (res.error === '10') {
          this.$notify({
            title: '保存成功',
            message: '个人资料修改成功',
            type: 'success'
          })
        } else {
          this.$notify({
            title: '保存失败',
            message: res.result,
            type: 'error'
          })
        }
      }
    },

    async saveClass() {
      console.log('begin')
      let res = await updateClass({class_id: this.ruleForm.classId})
      console.log('2')
      if (res.error === '10') {
        this.$notify({
          title: '保存成功',
          message: '班級保存成功',
          type: 'success'
        })
      } else {
        this.$notify({
          title: '保存失败',
          message: res.result,
          type: 'error'
        })
      }
      console.log('3')
      this.showCreateDialog=false
    },
  beforeMount () {
    console.log(this.$store.state.userInfo)
  }
}

}
</script>
<style lang="less">
.form-title {
  text-align: center;
  margin-bottom: 10px;
}
.tabs {
  margin: 0 auto;
  width: 70%;
  padding-top: 45px;
  font-size: 40px;
}
.tabs .tab-item {
  width: 50%;
  padding-top: 45px;
  font-size: 150%;
}
.save-btn {
    margin-left: 70%;
    background:#409EFF;
}
  .userinfo-item-value {
    display: flex;
  }

.profile-verify-code{
  width: 620px;
}
.profile-wrapper {
  padding-top: 45px;
  // width: 80%;
  margin: 0 auto;
  @media screen and (max-width: 768px){
    width: 96%;
    padding-top: 15px;
  }
  button {
    border-radius: 5;
  }
  .userinfo-content {
    padding: 30px 0 0 30px;
  }
  .userinfo-item {
    display: flex;
    size: medium;
    margin-bottom: 20px;

  }

  .userinfo-avatar {
    height: 150px;
    display: inline-block;
    cursor: pointer;
  }
  .save-btn {
    background: #000;
    color: #fff;
    margin-left: 30px;
    font-size: 20px;
  }
  .dialog {
    width: 500px;
    max-width: 100%;
    position: fixed;
    top: 120px;
    left: 50%;
    margin-left: -200px;
    background: #fff;
    box-shadow: 0 0 20px #bbb;
    border: 1px solid #bbb;
  }
  .dialog-title {
    background: #0195dd;
    padding: 15px 20px;
    color: #fff;
  }
  button.dialog-close {
    border: none;
    outline: none;
    background: transparent;
    color: #fff;
    font-size: 20px;
    float: right;
  }
  .dialog .form {
    width: 400px;
    margin: 40px auto;
  }
  .dialog .course-img {
    width: 160px;
    vertical-align: top;
    padding-top: 10px;
  }
  .dialog input {
    border-radius: 0;
  }
  .dialog .pick-file-btn {
    border: none;
    padding-left: 0;
    display: inline-block;
    cursor: pointer;
  }
  .dialog .submit-btn {
    margin-left: 200px;
    border-radius: 0;
    width: 120px;
  }
  .dialog .btn {
    border-radius: 0;
    width: 120px;
  }
  .dialog .date-picker {
    border-radius: 0;
  }
}
</style>
